import sys
import time
import json
from datetime import datetime
from selenium import webdriver
from selenium.common import exceptions
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
import urllib.parse
from mongoengine import *
# import sendMessage


sys.path.append('.')
sys.path.append('..')
disconnect()
# connect('weibo', host='localhost', port=27017)


class locationuser(Document):
    nickname = StringField()
    uid = StringField()
    gender = IntField()
    followerCount = IntField()
    postCount = IntField()
    fansCount = IntField()
    city = StringField()
    addTime = DateTimeField()
    updatetime = DateTimeField()
    searched = IntField()
    location = StringField()
    weibourl = StringField()
    weiboDetail = StringField()
    category = IntField()
    weiboDate = DateTimeField()
    dateStr = StringField()

def NewDriver():
    chrome_options = Options()
    chrome_options.add_argument("user-data-dir=" + path2  + 'locationbyurl')
    # print('run',a,b)
    driver = webdriver.Chrome(path, options=chrome_options)
    # print('run2',a,b)
    driver.maximize_window()
    return driver


def gotolocaltion():
    # driver.execute_script('window.open()')
    # windows = driver.window_handles
    # driver.switch_to.window(windows[1])
    # local = driver.find_element_by_class_name('ficon_cd_place')
    # local.click()
    locationinput = driver.find_element_by_tag_name('input')
    locationinput.send_keys(searchlocation)
    time.sleep(1)
    searchlist = driver.find_elements_by_tag_name('li')
    searchlist[0].click()
    time.sleep(3)

    # iframe = driver.find_elements_by_tag_name("iframe")[0]
    # driver.switch_to_frame(iframe)
    # time.sleep(1)

    driver.find_element_by_tag_name('body').send_keys(Keys.END)
    searchurl = driver.find_element_by_id('search_list').find_element_by_tag_name('iframe').get_attribute('src')
    # print(weibotext.get_attribute('href'))
    driver.get(str(searchurl))

def runuserlist():
    global url
    global location
    global cardlistindex
    # for index in range(0,26):
    userlistindx = 0
    time.sleep(2)
    # driver.switch_to.window(windows[0])
    # driver.find_element_by_id('app').send_keys(Keys.END)
    time.sleep(2)
    weibolist = driver.find_elements_by_class_name("card-list")[cardlistindex].find_elements_by_class_name("card")
    # weibolist[1]
    print(cardlistindex,len(weibolist))
    # templist = driver.find_elements_by_class_name("card-list")[cardlistindex].find_elements_by_class_name("card")
    # userlink = templist[5].find_element_by_class_name('weibo-top')
    # driver.execute_script("arguments[0].scrollIntoView();", userlink)
    time.sleep(2)
    # userlink.click()
    # userlistindx = len(weibolist)-1
    # while userlistindx > 0:
    # [0].find_elements_by_class_name('list_li')
    # print(len(userList),'okok')
    for index,item in enumerate(weibolist):
        try:
            templist = driver.find_elements_by_class_name("card-list")[cardlistindex].find_elements_by_class_name("card")
            userlink = templist[index].find_element_by_class_name('weibo-top').find_element_by_tag_name('a')
            detail = templist[index].find_element_by_class_name('weibo-text').get_attribute('textContent')
            weibodate =  templist[index].find_element_by_class_name('time').get_attribute('textContent')
    #         # userlink.click()
            infos = templist[index].find_elements_by_class_name('m-text-cut')
    # #         infos = infos.split("&")
            uid = ""
            nickname = ""
            nickname = infos[0].get_attribute('textContent')
    # #         for info in infos:
    # #             if info[0:3] == "uid":
    # #                 uid = info[4:]
    # #             if info[0:5] == "fnick":
    # #                 nickname = info[6:]
    # #             # print(uid,nickname,detail)
    # #         # uid = item.find_element_by_class_name('WB_info').get_attribute('usercard')[3:]
    # #         # nick = item.find_element_by_tag_name('img').get_attribute('alt')
    #         # driver.switch_to.window(windows[1])
            # userlink.click()
    #         uid = (driver.current_url).split("/")[4].split("?")[0]
            oneUser = locationuser.objects(location = location,nickname = nickname)
            if len(oneUser) == 0:
                newdata = locationuser(    
                    nickname = nickname,
                    # uid = uid,
                    addTime = datetime.now(),
                    updatetime = datetime.now(),
                    searched = 0,
                    location = location,
                    # weibourl = url,
                    category = 9,
                    weiboDetail = detail,
                    dateStr = weibodate
                    # weiboDate = weibodate
                )
                newdata.save()
            time.sleep(1)
            # driver.back()
            # userlistindx = userlistindx-1
            # time.sleep(2)
        except Exception as e:
            print(str(e),'error')
    try:
        time.sleep(2)
        driver.find_element_by_tag_name('body').send_keys(Keys.END)
        if len(driver.find_elements_by_class_name("card-list")) > cardlistindex+1:
            cardlistindex = cardlistindex + 1
        # try:
        #     driver.find_element_by_class_name('more_txt').click()
        # except:
        #     driver.find_element_by_class_name('next').click()
        # time.sleep(0.5)
        runuserlist()
        # if justStart < 10:
        #         driver.find_element_by_tag_name('body').send_keys(Keys.END)
        #         time.sleep(5)
        #         justStart = justStart + 1
        #         runuserlist()

        # else:
        #     time.sleep(2)
        #     try:
        #         driver.find_element_by_class_name('more_txt').click()
        #     except:
        #         driver.find_element_by_class_name('next').click()
        #     time.sleep(0.5)
        #     runuserlist()
        
    except:
        return


if __name__ == '__main__':
    location = sys.argv[1]
    locationtext = sys.argv[1] #保存名称
    searchlocation = sys.argv[2] #搜索名
    # print(a,b,c)
    mode = 1
    path = 'd:/work/weiboposition/python/chromedriver.exe'
    path2 = 'd:/work/weiboposition/profile/'
    if mode == 1:
        path = 'd:/weiboAdmin/python/chromedriver.exe'
        path2 = 'd:/weiboAdmin/profile/'
        #connect('weibo', host='192.168.1.176', port=27017)
        connect('weibo', host='localhost', port=27017)
    
    
    else:
        connect('weibo', host='localhost', port=27017)
    driver = NewDriver()
    # driver.execute_script('window.open()')
    # driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
    # windows = driver.window_handles
    # driver.switch_to.window(windows[1])
    # driver.switch_to.window(windows[0])
    driver.get("https://weibo.com")
    time.sleep(3)

    print("https://place.weibo.com/",'url')
    driver.get("https://place.weibo.com/")
    time.sleep(3)

    
    gotolocaltion()
    time.sleep(5)
    cardlistindex=2
    runuserlist()



    # while True:
    #     try:
    #         time.sleep(3)
    #         runuserlist()
    #     except:
    #         time.sleep(3)
    #         runuserlist()

    # while True:
    #     try:
    #         url = "https://weibo.com/{Uid}/{URL}?type=repost"
    #         print(url.format(Uid = uid,URL=repostID),'url')
    #         driver.get(url.format(Uid = uid,URL=repostID))
    #         # url = 'https://weibo.com/2042697783/IwTjWarB4?type=repost'
    #         # driver.get(url)
    #         time.sleep(3)
        # driver.execute_script('window.open()')
        # # driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
        # windows = driver.window_handles
        # driver.switch_to.window(windows[1])
        # driver.switch_to.window(windows[0])
        # time.sleep(1)
    #         try:
    #             getRepostUserList()
    #         except:
    #             getRepostUserList()
    #     except:
    #         # fansUrl = "https://weibo.com/{UID}/fans?cfs=600&relate=fans&t=1&f=1&type=&Pl_Official_RelationFans__90_page={page}#Pl_Official_RelationFans__90"
    #         # driver.get(fansUrl.format(UID=uid, page=1))
    #         # getFans(driver,uid,account)
    #         continue
